Sass Basics




Applications

There are a good many applications that will get you up and running with Sass in a few minutes for Mac, Windows, and Linux. You can download most of the applications for free but a few of them are paid apps (and totally worth it).

Command Line

When you install Sass on the command line, you'll be able to run the sass executable to compile .sass and .scss files to .css files. For example:

sass source/stylesheets/index.scss build/stylesheets/index.css

First install Sass using one of the options below, then run sass --version to be sure it installed correctly. If it did, this will include 1.22.1. You can also run sass --help for more information about the command-line interface.

Once it's all set up, go and play. If you're brand new to Sass we've set up some resources to help you learn pretty darn quick.

Learn More About Sass

Install Anywhere (Standalone)
You can install Sass on Windows, Mac, or Linux by downloading the package for your operating system from GitHub and adding it to your PATH. That’s all—there are no external dependencies and nothing else you need to install.
Install Anywhere (npm)

If you use Node.js, you can also install Sass using npm by running

npm install -g sass
However, please note that this will install the pure JavaScript implementation of Sass, which runs somewhat slower than the other options listed here. But it has the same interface, so it’ll be easy to swap in another implementation later if you need a bit more speed!
Install on Windows (Chocolatey)

If you use the Chocolatey package manager for Windows, you can install Dart Sass by running

choco install sass



Before you can use Sass, you need to set it up on your project. If you want to just browse here, go ahead, but we recommend you go install Sass first. Go here if you want to learn how to get everything setup.

Preprocessing

CSS on its own can be fun, but stylesheets are getting larger, more complex, and harder to maintain. This is where a preprocessor can help. Sass lets you use features that don't exist in CSS yet like variables, nesting, mixins, inheritance and other nifty goodies that make writing CSS fun again.

Once you start tinkering with Sass, it will take your preprocessed Sass file and save it as a normal CSS file that you can use in your website.

The most direct way to make this happen is in your terminal. Once Sass is installed, you can compile your Sass to CSS using the sass command. You'll need to tell Sass which file to build from, and where to output CSS to. For example, running sass input.scss output.css from your terminal would take a single Sass file, input.scss, and compile that file to output.css.

You can also watch individual files or directories with the --watch flag. The watch flag tells Sass to watch your source files for changes, and re-compile CSS each time you save your Sass. If you wanted to watch (instead of manually build) your input.scss file, you'd just add the watch flag to your command, like so:

sass --watch input.scss output.css

You can watch and output to directories by using folder paths as your input and output, and separating them with a colon. In this example:

sass --watch app/sass:public/stylesheets

Sass would watch all files in the app/sass folder for changes, and compile CSS to the public/stylesheets folder.


Variables

Think of variables as a way to store information that you want to reuse throughout your stylesheet. You can store things like colors, font stacks, or any CSS value you think you'll want to reuse. Sass uses the $ symbol to make something a variable. Here's an example:

SCSS Syntax

$font-stack:    Helvetica, sans-serif;
$primary-color: #333;

body {
  font: 100% $font-stack;
  color: $primary-color;
}

Sass Syntax

$font-stack:    Helvetica, sans-serif
$primary-color: #333

body
  font: 100% $font-stack
  color: $primary-color

CSS Output

body {
  font: 100% Helvetica, sans-serif;
  color: #333;
}



When the Sass is processed, it takes the variables we define for the $font-stack and $primary-color and outputs normal CSS with our variable values placed in the CSS. This can be extremely powerful when working with brand colors and keeping them consistent throughout the site.


Nesting

When writing HTML you've probably noticed that it has a clear nested and visual hierarchy. CSS, on the other hand, doesn't.

Sass will let you nest your CSS selectors in a way that follows the same visual hierarchy of your HTML. Be aware that overly nested rules will result in over-qualified CSS that could prove hard to maintain and is generally considered bad practice.

With that in mind, here's an example of some typical styles for a site's navigation:

SCSS Syntax

nav {
  ul {
    margin: 0;
    padding: 0;
    list-style: none;
  }

  li { display: inline-block; }

  a {
    display: block;
    padding: 6px 12px;
    text-decoration: none;
  }
}

Sass Syntax

nav
  ul
    margin: 0
    padding: 0
    list-style: none

  li
    display: inline-block

  a
    display: block
    padding: 6px 12px
    text-decoration: none


CSS Output

nav ul {
  margin: 0;
  padding: 0;
  list-style: none;
}
nav li {
  display: inline-block;
}
nav a {
  display: block;
  padding: 6px 12px;
  text-decoration: none;
}


You'll notice that the ul, li, and a selectors are nested inside the nav selector. This is a great way to organize your CSS and make it more readable.


Partials

You can create partial Sass files that contain little snippets of CSS that you can include in other Sass files. This is a great way to modularize your CSS and help keep things easier to maintain. A partial is simply a Sass file named with a leading underscore. You might name it something like _partial.scss. The underscore lets Sass know that the file is only a partial file and that it should not be generated into a CSS file. Sass partials are used with the @import directive.


Import

CSS has an import option that lets you split your CSS into smaller, more maintainable portions. The only drawback is that each time you use @import in CSS it creates another HTTP request. Sass builds on top of the current CSS @import but instead of requiring an HTTP request, Sass will take the file that you want to import and combine it with the file you're importing into so you can serve a single CSS file to the web browser.

Let's say you have a couple of Sass files, _reset.scss and base.scss. We want to import _reset.scss into base.scss.

SCSS Syntax

// _reset.scss
html,
body,
ul,
ol {
  margin:  0;
  padding: 0;
}
// base.scss
@import 'reset';
body {
  font: 100% Helvetica, sans-serif;
  background-color: #efefef;
}

Sass Syntax

// _reset.sass
html,
body,
ul,
ol
  margin:  0
  padding: 0

// base.sass
@import reset
body
  font: 100% Helvetica, sans-serif
  background-color: #efefef

CSS Output

html,
body,
ul,
ol {
  margin:  0;
  padding: 0;
}
body {
  font: 100% Helvetica, sans-serif;
  background-color: #efefef;
}





Notice we're using @import 'reset'; in the base.scss file. When you import a file you don't need to include the file extension .scss. Sass is smart and will figure it out for you.


Mixins

Some things in CSS are a bit tedious to write, especially with CSS3 and the many vendor prefixes that exist. A mixin lets you make groups of CSS declarations that you want to reuse throughout your site. You can even pass in values to make your mixin more flexible. A good use of a mixin is for vendor prefixes. Here's an example for transform.

SCSS Syntax

@mixin transform($property) {
  -webkit-transform: $property;
  -ms-transform: $property;
  transform: $property;
}
.box { @include transform(rotate(30deg)); }

Sass Syntax

=transform($property)
  -webkit-transform: $property
  -ms-transform: $property
  transform: $property
.box
  +transform(rotate(30deg))

CSS Output

.box {
  -webkit-transform: rotate(30deg);
  -ms-transform: rotate(30deg);
  transform: rotate(30deg);
}

To create a mixin you use the @mixin directive and give it a name. We've named our mixin transform. We're also using the variable $property inside the parentheses so we can pass in a transform of whatever we want. After you create your mixin, you can then use it as a CSS declaration starting with @include followed by the name of the mixin.


Extend/Inheritance

This is one of the most useful features of Sass. Using @extend lets you share a set of CSS properties from one selector to another. It helps keep your Sass very DRY. In our example we're going to create a simple series of messaging for errors, warnings and successes using another feature which goes hand in hand with extend, placeholder>CSS neat and clean.

SCSS Syntax

/* This CSS will print because %message-shared is extended. */
%message-shared {
  border: 1px solid #ccc;
  padding: 10px;
  color: #333;
}

// This CSS won't print because %equal-heights is never extended.
%equal-heights {
  display: flex;
  flex-wrap: wrap;
}

.message {
  @extend %message-shared;
}

.success {
  @extend %message-shared;
  border-color: green;
}

.error {
  @extend %message-shared;
  border-color: red;
}

.warning {
  @extend %message-shared;
  border-color: yellow;
}

Sass Syntax

/* This CSS will print because %message-shared is extended. */
%message-shared
  border: 1px solid #ccc
  padding: 10px
  color: #333


// This CSS won't print because %equal-heights is never extended.
%equal-heights
  display: flex
  flex-wrap: wrap


.message
  @extend %message-shared


.success
  @extend %message-shared
  border-color: green


.error
  @extend %message-shared
  border-color: red


.warning
  @extend %message-shared
  border-color: yellow

CSS Output

/* This CSS will print because %message-shared is extended. */
.message, .success, .error, .warning {
  border: 1px solid #ccc;
  padding: 10px;
  color: #333;
}

.success {
  border-color: green;
}

.error {
  border-color: red;
}

.warning {
  border-color: yellow;
}













What the above code does is tells .message, .success, .error, and .warning to behave just like %message-shared. That means anywhere that %message-shared shows up, .message, .success, .error, & .warning will too. The magic happens in the generated CSS, where each of these>CSS properties as %message-shared. This helps you avoid having to write multiple>HTML elements.

You can extend most simple CSS selectors in addition to placeholder>CSS.

Note that the CSS in %equal-heights isn't generated, because %equal-heights is never extended.


Operators

Doing math in your CSS is very helpful. Sass has a handful of standard math operators like +, -, *, /, and %. In our example we're going to do some simple math to calculate widths for an aside & article.

SCSS Syntax

.container {
  width: 100%;
}

article[role="main"] {
  float: left;
  width: 600px / 960px * 100%;
}

aside[role="complementary"] {
  float: right;
  width: 300px / 960px * 100%;
}

Sass Syntax

.container
  width: 100%


article[role="main"]
  float: left
  width: 600px / 960px * 100%


aside[role="complementary"]
  float: right
  width: 300px / 960px * 100%

CSS Output

.container {
  width: 100%;
}

article[role="main"] {
  float: left;
  width: 62.5%;
}

aside[role="complementary"] {
  float: right;
  width: 31.25%;
}

We've created a very simple fluid grid, based on 960px. Operations in Sass let us do something like take pixel values and convert them to percentages without much hassle.





SASS Example

We can simply create SASS and SCSS example. To do so, use the following steps:

Create a HTML file having the following code:

See this example:

Now create a file named "style.scss". It is similar to CSS file. The only one difference is that it is saved with ".scss" extension. Put the both file inside the root folder.

Now, execute the following code: sass --watch style.scss:style.css

SASS Instasll10

It will create a new CSS file named "style.css" inside the root folder automatically. Whenever you change the SCSS file, the style.css file will changed automatically.

The style.css file has the following code:

SASS Instasll11

Now execute the HTML file. It will read the CSS file and the output would be like this:

Output:

SASS Instasll12

Sass Style Guide

With more people than ever writing in Sass, it bears some consideration how we format it. CSS style guides are common, so perhaps we can extend those to cover choices unique to Sass.

Here are some ideas that I've been gravitating toward. Perhaps they are useful to you or help you formulate ideas of your own. If you're looking for more examples, Sass Guidelines is another good place to look.

Use Your Regular CSS Formatting Rules / Style Guide

This post is about Sass-specific stuff, but as a base to this, you should follow a whatever good CSS formatting guidelines you are already following. If you aren't yet, this roundup of style guides may help you. This includes things like:

  1. Be consistant with indentation
  2. Be consistant about where spaces before/after colons/braces go
  3. One selector per line, One rule per line
  4. List related properties together
  5. Have a plan for>
  6. Don't use ID's #hotdrama
  7. etc

List @extend(s) First

.weather {
  @extend %module; 
  ...
}

Knowing right off the bat that this>

Knowing when to use @extend versus @include can be a little tricky. Harry does a nice job of differentiating the two plus offers thoughts on how to use them both.

List @include(s) Next

.weather {
  @extend %module; 
  @include transition(all 0.3s ease-out);
  ...
}

Next up is your @includes for mixins and other functions. Again, this is nice to have near the top for reference, but also allows for overrides. You might also want to make the call on separating user-authored @includes and vendor-provided @includes.

List "Regular" Styles Next

.weather {
  @extend %module;
  @include transition(all 0.3s ease-out);
  background: LightCyan;
  ...
}

Adding out regular styles after the @extends and @includes allows us to properly override those properties, if needed.

Nested Pseudo

.weather {
  @extend %module;
  @include transition(all 0.3s ease-out);
  background: LightCyan;
  &:hover {
    background: DarkCyan;
  }
  &::before {
    content: "";
    display: block;
  }
  ...
}

Pseudo elements and pseudo>

Nested Selectors Last

.weather {
  @extend %module; 
  @include transition(all 0.3s ease);
  background: LightCyan;
  &:hover {
    background: DarkCyan;
  }
  &::before {
    content: "";
    display: block;
  }
  > h3 {
    @include transform(rotate(90deg));
    border-bottom: 1px solid white;
  }
}

Nothing goes after the nested stuff. And the same order as above within the nested selector would apply.

Never Write Vendor Prefixes

Vendor prefixes are a time-sensitive thing. As browsers update over time, the need for them will fall away. If you use Autoprefixer, when compiling Sass, then you should never have to write them.

Alternatively, you can use @mixins provided by libraries like Compass and Bourbon. Or roll your own. Although using @mixins for vendor prefixes is still less convenient than Autoprefixer and still requires some maintenance, it still beats having to write things out manually.

Maximum Nesting: Three Levels Deep

.weather {
  .cities {
    li {
      // no more!
    }
  }
}

Chances are, if you're deeper than that, you're writing a crappy selector. Crappy in that it's too reliant on HTML structure (fragile), overly specific (too powerful), and not very reusable (not useful). It's also on the edge of being difficult to understand.

If you really want to use tag selectors because the>

.weather
  > h3 {
    @extend %line-under;
  }
}

Maximum Nesting: 50 Lines

If a nested block of Sass is longer than that, there is a good chance it doesn't fit on one code editor screen, and starts becoming difficult to understand. The whole point of nesting is convenience and to assist in mental grouping. Don't use it if it hurts that.

Global and Section-Specific Sass Files Are just Table of Contents

In other words, no styles directly in them. Force yourself to keep all styles organized into component parts.

List Vendor/Global Dependencies First, Then Author Dependencies, Then Patterns, Then Parts

It ends up being an easy to understand table of contents:

/* Vendor Dependencies */
@import "compass";

/* Authored Dependencies */
@import "global/colors";
@import "global/mixins";

/* Patterns */
@import "global/tabs";
@import "global/modals";

/* Sections */
@import "global/header";
@import "global/footer";

The dependencies like Compass, colors, and mixins generate no compiled CSS at all, they are purely code dependencies. Listing the patterns next means that more specific "parts", which come after, have the power to override patterns without having a specificity war.

Break Into As Many Small Files As Makes Sense

There is no penalty to splitting into many small files. Do it as much as feels good to the project. I know I find it easier to jump to small specific files and navigate through them than fewer/larger ones.

...

@import "global/header/header/";
@import "global/header/logo/";
@import "global/header/dropdowns/";
@import "global/header/nav/";
@import "global/header/really-specific-thingy/";

I'd probably do this right in the global.scss, rather than have global @import a _header.scss file which has its own sub-imports. All that sub-importing could get out of hand.

Globbing might help if there starts to be too many to list.

Partials are named _partial.scss

This is a common naming convention that indicates this file isn't meant to be compiled by itself. It likely has dependencies that would make it impossible to compile by itself. Personally I like dashes in the "actual" filename though, like _dropdown-menu.scss.

Locally, Compile with Source Maps

In development, it probably doesn't matter which format you compile your Sass in (e.g. expanded, compressed, etc) locally as long as you are producing source maps.

It's a flag when you compile Sass:

$ sass sass/screen.scss:stylesheets/screen.css --sourcemap

Although you probably don't compile Sass like that typically, there is always some kind of way to configure the thing you're using to compile Sass to do it with source maps. When you have them, that means DevTools shows you where the Sass code is, which is super (duper) useful:

Here's a few relevant links on this:

In Deployment, Compile Compressed

Live websites should only ever have compressed CSS. And gzipped with far-our expires headers to boot.

Don't Even Commit .css Files

This might take some DevOps work, but it's pretty nice if .css files aren't even in your repository. The compilation happens during deployment. So the only thing you see in the repo are your nicely formatted hand authored Sass files. This makes the diffs useful as well. A diff is a comparison view of what changed provided by version control providers. The diff for a compressed CSS file is useless.

Be Generous With Comments

It is rare to regret leaving a comment in code. It is either helpful or easily ignorable. Comments get stripped when compiling to compressed code, so there is no cost.

.overlay {
  // modals are 6000, saving messages are 5500, header is 2000
  z-index: 5000; 
}

And speaking of comments, you may want to standardize on that. The // syntax in Sass is pretty nice especially for blocks of comments, so it is easier to comment/uncomment individual lines.

Variablize All Common Numbers, and Numbers with Meaning

If you find yourself using a number other than 0 or 100% over and over, it likely deserves a variable. Since it likely has meaning and controls consistency, being able to tweak it en masse may be useful.

If a number clearly has strong meaning, that's a use case for variablizing as well.

$zHeader: 2000;
$zOverlay: 5000;
$zMessage: 5050;

.header {
  z-index: $zHeader;
}
.overlay {
  z-index: $zOverlay;
}
.message {
  z-index: $zMessage;
}

Ideally, those numbers should probably be kept in a separate file @import-ed as a dependency. That way you can keep track of your whole z-index stack in one place. If, however, the variables are scoped to the>

.accordion {
  $accordion-header-color: $primary-color;
  $accordion-padding: 1em;
  
  @extend %module;
  @include transition(all 0.3s ease-out);
  background: $accordion-header-color;
  padding: $accordion-padding;
}

Variablize All Colors

Except perhaps white and black. Chances are a color isn't one-off, and even if you think it is, once it's in a variable you might see uses for it elsewhere. Variations on that color can often be handled by the Sass color functions like lighten() and darken() - which make updating colors easier (change in one place, whole color scheme updates).

Nest and Name Your Media Queries

The ability to nest media queries in Sass means 1) you don't have to re-write the selector somewhere else which can be error prone 2) the rules that you are overriding are very clear and obvious, which is usually not the case when they are at the bottom of your CSS or in a different file.

.sidebar {
  float: right;
  width: 33.33%;
  @include bp(mama-bear) {
    width: 25%;
  }
}

More on this and the importance of naming them well.

Shame Last

In your global stylesheet, @import a _shame.scss file last.

@import "compass"

...

@import "shame"

If you need to make a quick fix, you can do it here. Later when you have proper time, you can move the fix into the proper structure/organization. See more.

Final Output Is On You

Sass doesn't do anything you don't tell it to do, so claiming that Sass output is bloated is just claiming that you write bloated code. Write Sass such that the final CSS output is just as you would have written it without Sass.